<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
	$('#detailTable').bootstrapTable({
		 
		  //请求方法
               method: 'get',
        height:500,
               //类型json
               dataType: "json",
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/fee/detail/data",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	window.location = "${ctx}/fee/detail/form?id=" + row.id;
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该计费明细记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/fee/detail/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#detailTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
                  // selectMoney();
               },
               columns: [{
		        checkbox: true
		       
		    }
			,{
		        field: 'status',
		        title: '状态',
		        sortable: true,
		        formatter:function(value, row , index){
		        	return "<a href='${ctx}/fee/detail/form?id="+row.id+"'>"+jp.getDictLabel(${fns:toJson(fns:getDictList('detail_status'))}, value, "-")+"</a>";
		        }
		       
		    },{
                       field: 'feeType',
                       title: '收支类型',
                       sortable: true,
                       formatter:function(value, row , index){
							if(value.feeType == 0){
								return "收入";
							}else{
								return "支出";
							}
                       }

                   }
			,{
		        field: 'clearUnit',
		        title: '结算方',
		        sortable: true,
                formatter:function(value, row , index){
                    return value.name;
                }
		       
		    }
			,{
		        field: 'feeAgreement',
		        title: '计费协议',
		        sortable: true,
                       formatter:function(value, row , index){
                           return value.name;
                       }
		       
		    }
			,{
		        field: 'feeType',
		        title: '费用类型',
		        sortable: true,
                       formatter:function(value, row , index){
                           return value.name;
                       }
		       
		    }
			,{
		        field: 'busyDate',
		        title: '业务日期',
		        sortable: true
		       
		    }
			,{
		        field: 'payMoney',
		        title: '计费金额',
		        sortable: true
		       
		    }
			,{
		        field: 'clearingMoney',
		        title: '调整金额',
		        sortable: true
		       
		    }
			,{
		        field: 'codes',
		        title: '业务属性',
		        sortable: true
		       
		    }
			/*,{
		        field: 'feeData',
		        title: '数据源',
		        sortable: true
		       
		    }*/
			,{
		        field: 'updateReason',
		        title: '调整原因',
		        sortable: true
		       
		    }
			,{
		        field: 'updateClearingDate',
		        title: '调整时间',
		        sortable: true
		       
		    }
			,{
		        field: 'caculateDesc',
		        title: '计算描述',
		        sortable: true
		       
		    }
			,{
		        field: 'caculateValue',
		        title: '计算数值',
		        sortable: true
		       
		    }
			,{
		        field: 'remarks',
		        title: '备注信息',
		        sortable: true
		       
		    }
		     ]

		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#detailTable').bootstrapTable("toggleView");
		}
	  
	  $('#detailTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#detailTable').bootstrapTable('getSelections').length);
            $('#edit').prop('disabled', $('#detailTable').bootstrapTable('getSelections').length!=1);
        });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 1, 
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/fee/detail/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe 
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#detailTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		  $("#searchForm  .select-item").html("");
		  $('#detailTable').bootstrapTable('refresh');
		});


	});
		
  function getIdSelections() {
        return $.map($("#detailTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
  function getMoneySelections() {
        return $.map($("#detailTable").bootstrapTable('getSelections'), function (row) {
            return row.clearingMoney
        });
    }
  function getPayMoneySelections() {
        return $.map($("#detailTable").bootstrapTable('getSelections'), function (row) {
            return row.payMoney
        });
    }
  function getTypeSelections() {
        return $.map($("#detailTable").bootstrapTable('getSelections'), function (row) {
            return row.feeType.feeType
        });
    }
  function getStatusSelections() {
        return $.map($("#detailTable").bootstrapTable('getSelections'), function (row) {
            return row.status
        });
    }
  function getPayeeSelections() {
        return $.map($("#detailTable").bootstrapTable('getSelections'), function (row) {
            return row.clearUnit.name
        });
    }

  function deleteAll(){

		jp.confirm('确认要删除该计费明细记录吗？', function(){
			jp.loading();  	
			jp.get("${ctx}/fee/detail/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#detailTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})
          	   
		})
  }
  function edit(){
	  window.location = "${ctx}/fee/detail/form?id=" + getIdSelections();
  }
// checkbox点击事件
$(document).ready(function() {
    /*$("input[name='btSelectAll']").click(function () {
        selectMoney();
    })*/
   /* $("input[type='checkbox']").click(function (){
        selectMoney();
	})*/
    /*$('.bs-checkbox').click(function(){
        selectMoney();
    })*/
    $(function(){
        var s = $("input[type='checkbox']");
        s.each(function(i) {
//          alert(i);
            $(this).click(function(){
                if(this.checked==true){
                   // alert(this.value);
                    selectMoney();
                }
            });
        });
    })
})
//选中复选框计算选中项金额汇总
function selectMoney() {
	//var money = $("#selectMoney").text()*1;
    var a = document.getElementById("selectMoney").innerText;
    if(a == null || a == ""){
    	a=0.0*1;
	}else{
    	a=document.getElementById("selectMoney").innerText*1;
	}
    //alert(a);
    var tempIds = getIdSelections();
    $.ajax({
        url : "${ctx}/fee/detail/sumPayMoney",
        data : {		 //参数值
            "ids" :tempIds
        },
        type:"post",
        success : function(data) {
        	//alert(data);
        	var clear = data * 1;
            $("#selectMoney").text("￥"+(Number(a+clear)).toFixed(2));
        },
        error : function(data){
            alert("操作失败!");
        }
    });

}

//结算按钮的事件
function goBalance() {
    var tempStatus = getStatusSelections();//状态
    var tempPayee = getPayeeSelections();//结算方
    var tempIds = getIdSelections();//复选框的ID
    var tempType = getTypeSelections();//收支类型
    var sc = "";	//机构名称变量
    var textStatus = "";//状态
    var textType = "";//收支类型
    if (tempIds == null || tempIds == "") {
        alert("请至少选择一条数据");
        return;
    }
    //判断状态和结算方是否相同
    var _status = tempStatus.toString().split(",");
    var _payee = tempPayee.toString().split(",");
	var _type = tempType.toString().split(",");
    for (var i = 0; i < _payee.length; i++){
        if (!_payee[i]) {
            continue;
        }
        //判断结算方是否相同
        var tempSc = _payee[i];
        if (!sc) {
            sc = tempSc;	//第一个元素赋值到sc
        } else if (sc != tempSc) {//上一个元素sc与本次循环的值不相等，不是同一个机构
            alert("请选择相同结算方!");
            return;
        }
        //判断状态是否相同
        var tempStr = _status[i];
        if(tempStr == 0 ){
            if (!textStatus) {
                textStatus = tempStr;	//第一个元素赋值到sc
            } else if (textStatus != tempStr) {//上一个元素sc与本次循环的值不相等，不是同一个机构
                alert("请选择相同状态的明细!");
                return;
            }
        }else{
            alert("状态为未结算的明细才能进行结算操作");
            return;
        }
        //判断收支类型是否相同
		var type = _type[i];
        if(!textType){
            textType = type;
		}else if(textType != type){
            alert("请选择相同的收支类型!");
            return;
		}
    }
	//判断收入还是支出，生成相应的结算单
    if(textType.trim()==0){//生成应收结算单 参数：结算方
    $("#receiveModal").modal("show");
        $.ajax({
            url : "${ctx}/fee/detail/addPayable?ids="+tempIds,
            data : {		 //参数值
               // "ids" :tempIds,
            },
            type:"post",
            success : function(data) {
                if(data){
                    var list = eval(data);
                    var clearMoney = 0*1;//结算单的结算金额
                    var adjustMoney = 0 * 1;//调整金额
                    var clearUnit = "";
                    var appendEle = $("#receiveDetailTbody");
                    appendEle.empty();
                    $.each(list,function(index,term){
                        var addTr = $("<tr id='"+term.id+"'></tr>");
                        addTr.appendTo(appendEle);
                        var td = ("<td>"+"<input id='"+term.id+"'  type='checkbox' class='i-checks'>"+"</td>");
                        addTr.append(td);
                        addTr.append($('<td></td>').text(index+1));
                        addTr.append($('<td></td>').text(term.busyDate));
                        addTr.append($('<td></td>').text(term.feeAgreement.name));
                        addTr.append($('<td></td>').text(term.feeType.name));
                        addTr.append($("<td id='"+term.id+"_receiveMoney'>"+"</td>").text(Number(term.payMoney).toFixed(2)));
                        addTr.append($("<td id='"+term.id+"_receiveclearingMoney'>"+"</td>").text(Number(term.clearingMoney).toFixed(2)));
                        addTr.append("<td id='"+term.id+"_adjustSpread'>"+"</td>");
                        addTr.append("<td><a href='#' onclick=\"jp.openDialogView('查看费用明细', '${ctx}/fee/detail/form?id="+term.id+"','800px', '500px')\" class='btn btn-info btn-xs' ><i class='fa fa-search-plus'></i> 查看</a>"
                            +"&nbsp;<input onclick=\"deleteInPage('receive','"+term.id+"','"+tempIds+"')\"  type='button' value='删除' class='btn btn-danger btn-xs'>"+"</td>");
                        //clearMoney += term.payMoney;
                        //获取调整金额
                        adjustMoney = term.clearingMoney;
                        //判断调整金额是否为空
                        if (adjustMoney) {
                            clearMoney += term.clearingMoney;
                            //获取计费金额
                            var payMoney = term.payMoney;
                            //计算调整差额
                            var adjustSpread = Math.abs(payMoney-adjustMoney);
                            $("#"+term.id+"_adjustSpread").text(Number(adjustSpread).toFixed(2));
                        }else{
                            clearMoney += (adjustMoney+term.payMoney);
                        }
                        //alert("调整金额:"+adjustMoney+",结算金额："+clearMoney);
                       /* var tempId = ids.value;
                        tempId += term.id;
                        tempId += ",";
                        ids.value = tempId;*/
                        //获取结算方
                        clearUnit = term.clearUnit.name;
                    })
                    $("#modalreceiveClearUnit").val(clearUnit);
                    //如果结算金额异常，则置为0
                    clearMoney = clearMoney < 0 ? 0 : clearMoney;
                    $("#receiveMoney").val(Number(clearMoney).toFixed(2));
                    layer.closeAll('loading');
                    //var selectMoney = $("#selectMoney").text();
                    //selectMoney = selectMoney.substring(1);
                    payConfirm('receive',tempIds,sc,clearMoney);
                    layer.closeAll('loading');
                }else{
                    //结算金额置为0
                    $("#money").val(clearMoney);
                    layer.closeAll('loading');
                }
            },
            error : function(){
                alert("操作失败!");
                layer.closeAll('loading');
            }
        });
    }else{//生成应付结算单
    $("#payModal").modal("show");
        $.ajax({
            url: "${ctx}/fee/detail/addPayable?ids="+tempIds,
            data: {
            },
            type: "post",
            success: function (data) {
                if (data) {
                    var list = eval(data);
                    var clearMoney = 0 * 1;//结算单的结算金额
                    var adjustMoney = 0 * 1;//调整金额
                    var clearUnit = "";
                    var appendEle = $("#payDetailTbody");
                    appendEle.empty();
                    $.each(list, function (index, feePayableDetail) {
                        var addTr = $("<tr id='" + feePayableDetail.id + "'></tr>");
                        addTr.appendTo(appendEle);
                        var td = ("<td>" + "<input id='" + feePayableDetail.id + "'  type='checkbox' class='i-checks'>" + "</td>");
                        addTr.append(td);
                        addTr.append($('<td></td>').text(index + 1));
                        addTr.append($('<td></td>').text(feePayableDetail.busyDate));
                        addTr.append($('<td></td>').text(feePayableDetail.feeAgreement.name));
                        addTr.append($('<td></td>').text(feePayableDetail.feeType.name));
                        addTr.append($("<td id='" + feePayableDetail.id + "_payMoney'>" + "</td>").text(Number(feePayableDetail.payMoney).toFixed(2)));
                        addTr.append($("<td id='" + feePayableDetail.id + "_payclearingMoney'>" + "</td>").text(Number(feePayableDetail.clearingMoney).toFixed(2)));
                        addTr.append("<td id='" + feePayableDetail.id + "_adjustSpread'>" + "</td>");
                        addTr.append("<td><a href='#' onclick=\"jp.openDialogView('查看费用明细', '${ctx}/fee/detail/form?id=" + feePayableDetail.id + "','800px', '500px')\" class='btn btn-info btn-xs' ><i class='fa fa-search-plus'></i> 查看</a>"
                            + "&nbsp;<input onclick=\"deleteInPage('pay','" + feePayableDetail.id + "','"+tempIds+ "')\"  type='button' value='删除' class='btn btn-danger btn-xs'>" + "</td>");
                        //获取调整金额
                        adjustMoney = feePayableDetail.clearingMoney;
                        //判断调整金额是否为空
                        if (adjustMoney) {
                            clearMoney += feePayableDetail.clearingMoney;
                            //获取计费金额
                            var payMoney = feePayableDetail.payMoney;
                            //计算调整差额
                            var adjustSpread = Math.abs(payMoney - adjustMoney);
                            $("#" + feePayableDetail.id + "_adjustSpread").text(Number(adjustSpread).toFixed(2));
                        } else {
                            clearMoney += (adjustMoney + feePayableDetail.payMoney);
                        }
                       /* var tempId = ids.value;
                        tempId += feePayableDetail.id;
                        tempId += ",";
                        ids.value = tempId;*/
                        //获取结算方
                        clearUnit = feePayableDetail.clearUnit.name;
                    })
                    $("#modalpayClearUnit").val(clearUnit);
                    //如果结算金额异常，则置为0
                    clearMoney = clearMoney < 0 ? 0 : clearMoney;
                    $("#payMoney").val(Number(clearMoney).toFixed(2));
                    //var selectMoney = $("#selectMoney").text();
                    //selectMoney = selectMoney.substring(1);
                    payConfirm('pay',tempIds,sc,clearMoney);
                    layer.closeAll('loading');
                } else {
                    layer.closeAll('loading');
                }
            },
            error: function () {
                alert("操作失败!");
                layer.closeAll('loading');
            }
        });

    }
}

//支付结算的确定按钮点击事件
function payConfirm(type,tempIds,unit,clearMoney){
    $("#"+type+"ConfirmClose").unbind("click");//先清除click事件
    $("#"+type+"ConfirmClose").click(function(){
        var remark = $("#"+type+"Remark").val();
        var url="";
        if(type=="pay"){
            url = "${ctx}/fee/payable/balanceSave?ids="+tempIds+"&clearUnit="+unit+"&clearMon="+clearMoney+"&remark="+remark;
        }else if(type=="receive"){
            url = "${ctx}/fee/receivables/balanceSave?ids="+tempIds+"&clearUnit="+unit+"&clearMon="+clearMoney+"&remark="+remark;
        }else{
            alert("数据异常!");
            return;
        }
        $("#"+type+"Modal").modal("hide");
        $.ajax({
            url: url,
            data: {//"ids": tempIds,"clearUnit":unit,"clearMon":clearMoney,"remark":remark
				 },
            type: "post",
            success: function (data) {
                if(data=="0"){
                    alert("保存成功!");
                    $("#searchForm").submit();
                }else if(data=="1"){
                    alert("数据异常!");
                }
            },
            error: function(){
                alert("提交保存时数据异常!");
            }
        })
    });
}
//页面上删除明细  ids去掉改明细的id，重置结算金额
function deleteInPage(type,id,ids) {
    if (confirm("确定要删除吗？")) {
        //获取原来的结算金额
        var clearMoney = $("#"+type+"Money").val() * 1;
        var balanceMoney = 0 * 1;
        //获取计费金额
        var payMoney = $("#" + id + "_"+type+"Money").text() * 1;
        //获取结算金额
        var adjustMoney = $("#" + id + "_"+type+"clearingMoney").text() * 1;
        if (adjustMoney) {//判断调整金额是否为空
            //重新计算结算单的结算金额
            balanceMoney = clearMoney - adjustMoney;
        } else {
        //重新计算结算单的结算金额
            balanceMoney = clearMoney - payMoney;
        }
        $("#"+type+"Money").val((Number(balanceMoney)).toFixed(2));
        $("#"+type+"DetailTbody tr").each(function () {
            var trId = $(this).attr("id");
            if (trId == id) {
            //获得页面原来的ids
                var str = ids;
                var _str = str.trim().split(",");
                str = "";
                for (var i = 0; i < _str.length; i++) {
                    if (_str[i] == id) {
                    //ids删除id,ids中原来包含的id置为空字符串
                        _str[i] = "";
                    }
                //重新追加ids的值
                    str += _str[i] + ",";
                }
                var unit = $("#modal"+type+"ClearUnit").val();
                payConfirm(type,str,unit,balanceMoney);
            //tbody删除id= 传入id的一行数据
                    $(this).remove();
                return;
            }
        })
    }
}
</script>